<template>
  <div class="container">
    <el-form :model="dataForm" @submit.native.prevent>
      <el-form-item>
        <el-row class="row-bg" justify="space-around" type="flex">
          <el-col :span="22">
            <el-input
                ref="search-ref"
                v-model="dataForm.param"
                :type="dataForm.type"
                clearable
                placeholder="[F2]:会员码/电话号码/加油卡号"
                prefix-icon="el-icon-user-solid"
                suffix-icon="el-icon-phone"
                @change="handleSearch">
            </el-input>
          </el-col>
          <el-col :span="2" style="text-align:center;">
            <el-tooltip content="读卡" placement="top">
              <el-button circle icon="el-icon-bank-card" size="mini" type="success" @click="readCard"></el-button>
            </el-tooltip>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <!-- 会员选择框-当一个手机号码对应多个会员时 -->
    <el-dialog
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="chooseDialogVisible"
        append-to-body
        title="双击选择对应的会员"
        width="700px">
      <!-- 会员列表 -->
      <el-table :data="memberList" height="200" style="width: 100%;" @row-dblclick="handleDBClick">
        <el-table-column align="left" label="#" type="index" width="50"></el-table-column>
        <el-table-column label="用户昵称" prop="nickName" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="当前金币" prop="totalCoins"></el-table-column>
        <el-table-column align="center" label="累计消费" prop="totalConsumptionAmount"></el-table-column>
        <el-table-column align="center" label="注册日期" prop="registrationDate" width="180"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import {getMemberInfoByOpenid, getMemberInfoByPhone, getUsableCoupons} from '@/api/member'
import {getCardInfo} from '@/api/card'
import {readCardNo} from '@/utils/cardreader'
import {getMemberPoints} from '../../../api/member'

var Mousetrap = require('mousetrap')
var moment = require('moment')
export default {
  name: 'CartRightSearchBar',
  data () {
    return {
      dataForm: {
        param: '',
        type: 'text'
      },
      memberList: [],
      chooseDialogVisible: false
    }
  },
  computed: {
    ...mapGetters([
      'stationId',
      'operator',
      'cartList',
      'cartVisible',
      'cardUid',
      'cartGoodsAmount'
    ])
  },
  mounted () {
    this.bindKeyboard()
  },
  methods: {
    handleSearch (value) {
      console.log('handleSearch')
      console.log(value)
      if (!value) {
        console.log('clear member info')
        // 清空会员信息
        this.setCartMemberInfo(null)
        this.setCartCardInfo(null)
        return false
      }
      document.activeElement.blur()
      if (value.length === 11) {
        // 如果长度为11，判断为电话号码
        console.log('getMemberInfoByPhone')
        this.dataForm.type = 'text'
        this.memberList = []
        getMemberInfoByPhone(value).then(res => {
          console.log(res)
          this.memberList = res.data
          if (res.data.length > 1) {
            this.chooseDialogVisible = true
          } else if (res.data.length === 1) {
            let memberInfo = res.data[0]
            getMemberPoints(memberInfo.id, this.stationId).then(res => {
              console.log(res)
              memberInfo.totalPoints = res.data
              this.setCartMemberInfo(memberInfo)
            })
          }
        }).catch(err => {
          console.log(err)
          this.$message.warning('电话号码查不到对应的会员！')
        })
      } else if (value.length === 12) {
        // 如果长度为12位，则判断为加油卡
        console.log('这是加油卡')
        console.log(value)
        getCardInfo(value).then(res => {
          console.log(res)
          if (res.data.cardStatus !== '1') {
            this.$message.warning('该卡处于' + res.data.cardStatusName + '状态')
            return false
          }
          this.setCartCardInfo(res.data)
        }).catch(err => {
          console.log(err)
          this.$message.warning(err || '查找失败')
        })
      } else {
        // 判断为会员码
        this.dataForm.type = 'password'
        console.log('getMemberInfoByOpenid')
        getMemberInfoByOpenid(value).then(res => {
          console.log(res)
          let memberInfo = res.data
          getMemberPoints(memberInfo.id, this.stationId).then(res => {
            console.log(res)
            memberInfo.totalPoints = res.data
            this.setCartMemberInfo(memberInfo)
          })
        }).catch(err => {
          console.log(err)
        })
      }
    },
    // 双击事件处理
    handleDBClick (row, column, event) {
      console.log('handleDBClick')
      console.log(row)
      let memberInfo = row
      getMemberPoints(memberInfo.id, this.stationId).then(res => {
        console.log(res)
        memberInfo.totalPoints = res.data
        this.setCartMemberInfo(memberInfo)
      })
      this.chooseDialogVisible = false
    },
    // 确定会员信息
    setCartMemberInfo (data) {
      this.$store.dispatch('setMemberInfo', data)
      if (data) {
        // 获取会员可用优惠券信息
        var tmpList = this.cartList.filter(item => item.type === 'oil')
        let params = {
          memberId: data.id,
          stationId: this.stationId,
          amount: this.cartGoodsAmount,
          fuelName: 'commodity',
          litre: 0.00,
          fuelTime: moment().format('YYYY-MM-DD HH:mm:ss')
        }
        if (tmpList.length > 0) {
          params = {
            memberId: data.id,
            stationId: this.stationId,
            amount: tmpList[0].data.amount,
            fuelName: tmpList[0].data.fuelName,
            litre: tmpList[0].data.litre,
            fuelTime: tmpList[0].data.endTime
          }
        }
        console.log('getUsableCoupons')
        console.log(params)
        getUsableCoupons(params).then(res => {
          console.log(res)
          this.$store.dispatch('setCouponList', res.data)
          setTimeout(() => {
            this.$bus.$emit('autoSelectCoupons')
          }, 200)
        }).catch(err => {
          console.log(err)
        })
      }
    },
    // 确定卡信息
    setCartCardInfo (data) {
      console.log('setCartCardInfo')
      console.log(data)
      this.$store.dispatch('setMemberInfo', null)
      this.$store.dispatch('setCardInfo', data)
      // 获取储值卡绑定会员的可用加油券
      if (data.memberId) {
        // 获取会员可用优惠券信息
        var tmpList = this.cartList.filter(item => item.type === 'oil')
        if (tmpList.length > 0) {
          var params = {
            cardUid: data.uid,
            memberId: data.memberId,
            stationId: this.stationId,
            amount: tmpList[0].data.amount,
            fuelName: tmpList[0].data.fuelName,
            litre: tmpList[0].data.litre,
            fuelTime: tmpList[0].data.endTime
          }
          console.log('getUsableCoupons')
          console.log(params)
          getUsableCoupons(params).then(res => {
            console.log(res)
            this.$store.dispatch('setCouponList', res.data)
            setTimeout(() => {
              this.$bus.$emit('autoSelectCoupons')
            }, 200)
          }).catch(err => {
            console.log(err)
          })
        }
      } else {
        setTimeout(() => {
          this.$bus.$emit('autoSelectCoupons')
        }, 200)
      }
    },
    readCard () {
      var cardNo = readCardNo()
      if (cardNo) {
        this.dataForm.param = cardNo
        getCardInfo(cardNo).then(res => {
          console.log(res)
          if (res.data.cardStatus !== 1) {
            this.$message.warning('该卡处于' + res.data.cardStatusName + '状态')
            return false
          }
          this.setCartCardInfo(res.data)
        }).catch(err => {
          console.log(err)
          this.$message.warning(err || '查找失败')
        })
      } else {
        this.$message.warning('无法识别到卡片！')
      }
    },
    bindKeyboard () {
      Mousetrap.bind('f2', () => {
        if (this.cartVisible) {
          // 焦点聚焦在油枪输入框内
          this.$nextTick(() => {
            this.$refs['search-ref'].focus()
          })
        }
      })
    }
  }
}
</script>

<style>

</style>
